import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class UiAppBar extends StatefulWidget implements PreferredSizeWidget {
  const UiAppBar({
    super.key,
    this.transition = false,
    this.transitionNotify,
    this.transitionDistance = 80,
    this.transitionMinDistance = 0,
    this.backgroundColor,
    this.foregroundColor,
    this.toolbarHeight,
    this.toolbarTextStyle,
    this.elevation,
    this.scrolledUnderElevation,
    this.leading,
    this.leadingWidth,
    this.title,
    this.titleBuilder,
    this.titleSpacing,
    this.titleTextStyle,
    this.actions,
    this.shape,
    this.systemOverlayStyle,
    this.clipBehavior,
    this.notificationPredicate,
  });

  /// 过渡效果
  final bool transition;

  /// 过渡距离 透明度 = 滚动距离/过渡距离
  final double transitionDistance;

  /// 过渡最小出发距离
  final double transitionMinDistance;

  /// 过渡通知 返回当前的透明度
  final Function(double opacity)? transitionNotify;

  /// 背景颜色
  final Color? backgroundColor;

  /// 前景颜色
  final Color? foregroundColor;

  /// 高度
  final double? toolbarHeight;

  /// 工具条样式
  final TextStyle? toolbarTextStyle;

  /// 阴影（底部边框）
  final double? elevation;

  /// 滚动阴影（底部边框）
  final double? scrolledUnderElevation;

  /// 左侧组件
  final Widget? leading;

  /// 左侧组件宽度
  final double? leadingWidth;

  /// 标题
  final Widget? title;
  final Widget Function(BuildContext)? titleBuilder;

  /// 标题样式
  final TextStyle? titleTextStyle;

  /// 标题间距
  final double? titleSpacing;

  /// 右侧组件
  final List<Widget>? actions;

  /// 形状
  final ShapeBorder? shape;

  /// 系统叠加样式
  final SystemUiOverlayStyle? systemOverlayStyle;

  /// 裁剪行为
  final Clip? clipBehavior;

  final Function(ScrollNotification)? notificationPredicate;

  @override
  State<UiAppBar> createState() => _UiAppBarState();

  @override
  Size get preferredSize => Size(
        double.infinity,
        toolbarHeight ?? UiTheme.toolbarHeight,
      );
}

class _UiAppBarState extends State<UiAppBar> {
  double headerOpacity = 0;
  @override
  Widget build(BuildContext context) {
    Widget appbar = AppBar(
      backgroundColor:
          (widget.backgroundColor ?? AppBarTheme.of(context).backgroundColor)
              ?.withOpacity(headerOpacity),
      foregroundColor: widget.foregroundColor,
      leading: widget.leading,
      leadingWidth: widget.leadingWidth,
      title: widget.transition
          ? Opacity(
              opacity: headerOpacity,
              child: widget.title,
            )
          : widget.title,
      titleTextStyle: widget.titleTextStyle,
      titleSpacing: widget.titleSpacing,
      actions: widget.actions,
      notificationPredicate: (notification) {
        var metrics = notification.metrics;
        double alignmentY = -1 + metrics.pixels / metrics.maxScrollExtent;

        double offsetY =
            notification.metrics.pixels - widget.transitionMinDistance;
        double opacity = max(0,
            min(1, alignmentY > 0 ? offsetY / widget.transitionDistance : 0));

        if (opacity != headerOpacity) {
          setState(() {
            headerOpacity = opacity;
          });
          widget.transitionNotify?.call(headerOpacity);
        }

        return widget.notificationPredicate?.call(notification) ?? true;
      },
      elevation: widget.transition ? 0 : widget.elevation,
      scrolledUnderElevation: widget.scrolledUnderElevation,
      toolbarHeight: widget.toolbarHeight,
      toolbarTextStyle: widget.toolbarTextStyle,
      shape: widget.shape,
      systemOverlayStyle: widget.systemOverlayStyle,
      clipBehavior: widget.clipBehavior,
    );
    return appbar;
    // return widget.transition
    //     ? Opacity(
    //         opacity: headerOpacity,
    //         child: appbar,
    //       )
    //     : appbar;
  }
}
